"""
在线词典 ： 客户端 发请求 得结果 展示
"""
import sys
from socket import *
import getpass
import re


# 具体向服务端发起请求
class Handle:
    @staticmethod
    def check(info):
        if re.findall("^\w{4,12}$", info):
            return True

    def __init__(self):
        self.server_address = ("127.0.0.1", 8888)
        self.sock = self._connect()

    def _connect(self):
        sock = socket()
        sock.connect(self.server_address)
        return sock

    # 发出退出信号
    def do_exit(self):
        self.sock.send(b"E")
        self.sock.close()
        sys.exit("谢谢使用")

    # 请求注册
    def do_register(self, name, passwd):
        if Handle.check(name) and Handle.check(passwd):
            request = "R\t%s\t%s" % (name, passwd)
            self.sock.send(request.encode())  # 发请求
            res = self.sock.recv(128)  # 收响应
            if res == b'T':
                print("注册成功！")
            else:
                print("注册失败！")
        else:
            print("用户名或密码需为4-12位数字字母下划线。")

    # 请求登录
    def do_login(self, name, passwd):
        request = "L\t%s\t%s" % (name, passwd)
        self.sock.send(request.encode())  # 发请求
        res = self.sock.recv(128)  # 收响应
        if res == b'T':
            print("登录成功！")
            return True
        else:
            print("登录失败！")

    # 查询单词
    def do_query(self):
        # 　循环查询单词
        while True:
            word = input("要查询的单词:")
            if not word or word == "##":
                break
            request = "Q\t" + word
            self.sock.send(request.encode())  # 发送请求
            data = self.sock.recv(1024)
            # data : b"T\txxxxxx xxx" b"F"
            if data == b"F":
                mean = "Not Found!"
            else:
                mean = data.decode().split("\t", 1)[1]
            print("%s : %s\n" % (word, mean))

    # 获取历史记录
    def do_hist(self):
        self.sock.send(b"H")
        data = self.sock.recv(1024 * 10)
        # data :  b"F"
        if data == b"F":
            print("您还没有查询记录。")
        else:
            # data b"T\tname,word,time;name..."
            rows = data.decode().split("\t")[1].split(';')
            for row in rows:
                print(row)


# 与用户交互
class DICTView:
    def __init__(self):
        self.handle = Handle()

    # 输入用户名密码
    def _input_info(self):
        name = input("User:")
        passwd = getpass.getpass()  # 只能在终端
        return name, passwd

    # 二级界面
    def __menu_2(self):
        while True:
            print("""
    ============ 查询界面 ============
     1. 查单词   2. 历史记录   3. 注销
    =================================
            """)
            cmd = input("请输入选项:")
            if cmd == "1":
                self.handle.do_query()
            elif cmd == "2":
                self.handle.do_hist()
            elif cmd == "3":
                break
            else:
                print("请输入正确选项！")

    # 一级界面
    def __menu_1(self):
        while True:
            print("""
        ========== 登录界面 ==========
         1. 登录   2. 注册   3. 退出
        =============================
            """)
            cmd = input("请输入选项:")
            if cmd == "1":
                if self.handle.do_login(*self._input_info()):
                    self.__menu_2()
            elif cmd == "2":
                self.handle.do_register(*self._input_info())
            elif cmd == "3":
                self.handle.do_exit()
            else:
                print("请输入正确选项！")

    def main(self):
        self.__menu_1()


if __name__ == '__main__':
    dict = DICTView()
    dict.main()